<template>
  <div class="setAuthModal" v-if="Object.values(checkList).length > 0">
    <div class="main">
      <div class="item" v-for="(item,index) in userRouter" :key="index" >
        <p class="title">{{item.title}}:</p>
        <!-- {{ checkList[item.name] }} -->
        <el-checkbox-group v-model="checkList[item.name]" >
          <!-- :true-label="1"
          :false-label="0"-->
          <el-checkbox 
          v-for="(t,i) in item.children" 
          v-show="t.name != 'userManage'"
           :key="i" :label="t.name">{{ t.title }}</el-checkbox>
        </el-checkbox-group>
      </div>
    </div>

    <div class="footer">
      <el-button @click="()=>$emit('close')">取 消</el-button>
      <el-button type="primary" @click="sureBtn">确 定</el-button>
    </div>
  </div>
</template>

<script>
import { roleRouter } from "@/router/index";
// import { roleTemplateRouter as userRouter } from "@/router/routerConfig";
import { getUserAuthority,saveUserAuthority } from "@/api/set";
import { deepClone } from "@/utils/tool";
export default {
  name: "setAuthModal",
  props:{
    userId:{
      type:String,
      default:''
    }
  },
  data() {
    return {
      userRouter: {},
      checkList: {}
    };
  },
  mounted() {
    this.initial();
    return;
  },
  methods: {
    async initial() {
      if(!this.userId) { 
        this.$emit('close');
        return;
      };
      let result = await getUserAuthority({
        user_id:this.userId
      });
      if (result.code == 200) {
        /**
         * 循环前端路由配置来与后端返回的权限路由匹配 
         * 要处理的核心逻辑:后续前端增加新路由页 后端返回的权限路由没有匹配的话就新增，默认不选中
         * 
         * 前端新增路由页分两种情况:
         * 1.某一模块功能中增加一个新的子路由页
         * 2.增加一个新的模块功能
         * **/
        this.userRouter = JSON.parse(result.data.admin_role);
        let routerList = {};
        Object.values(roleRouter).forEach(item => {
          let name = item.name;
          if (this.userRouter[name]) {
            //存在权限 需要判断是否有前端新增的子项
            //当前前端路由
            let newchilds = item.children;
            //后台存储路由 
            let backendChilds = this.userRouter[name].children;

            //筛选出前端新增的子路由
            let newAddChilds = newchilds.filter(item => {
              let name = item.name;
              return !backendChilds.find(t => t.name == name);
            });

            //如果newAddChilds长度大于0 则存在新加的 然后默认追加
            newAddChilds.forEach(item=>{
              this.userRouter[name].children.push({
                name:item.name,
                title:item.meta.title,
                status:0,
              })
            });
            
            routerList[name] = this.userRouter[name].children
              .filter(t => t.status == 1)
              .map(t => t.name);
          } else {
            //前端新增的权限
            console.log("前端新增的权限路由", item);
            this.userRouter[name] = {
              name,
              title: item.meta.title,
              status: 1,
              children: item.children.map(item => {
                let name = item.name;
                return {
                  name,
                  title: item.meta.title,
                  status: 0
                };
              })
            };
            routerList[name] = item.children
              .filter(t => t.status == 1)
              .map(t => t.name);
          }
        });
        this.checkList = routerList;
        // console.log("this.userRouter", this.userRouter);
      }else{
        this.$emit('close');
      }
    },
   async sureBtn() {
      // console.log("this.checkList", this.checkList);
      //根据checkList生成新的权限对象
      let newUserRouter = deepClone(this.userRouter);
      Object.keys(this.checkList).forEach(key => {
        let value = this.checkList[key];
        if (value.length == 0) {
          //全部取消勾选 直接父级状态改为不显示
          newUserRouter[key].status = 0;
          newUserRouter[key].children = newUserRouter[key].children.map(
            t => {
              return {
                ...t,
                status: 0
              };
            }
          );
        } else {
          //遍历子级依次赋值
          newUserRouter[key].status = 1;
          newUserRouter[key].children.forEach(item => {
            let name = item.name;
            if (value.includes(name)) {
              //当前节点勾选显示
              item.status = 1;
            } else {
              //当前节点不勾选
              item.status = 0;
            }
          });
        }
      });
      // console.log("修改过后的用户权限路由",newUserRouter); 

      let result = await saveUserAuthority({
        user_id:this.userId,
        auth_detail:JSON.stringify(newUserRouter) 
      });
      if(result.code == 200){
        this.$message({
          type: "success",
          message: "设置权限成功"
        });
        this.$emit('close');
      }

    }
  }
};
</script>

<style lang="scss" scoped>
.setAuthModal {
  display: flex;
  flex-direction: column;
  height: 70vh;
  .main {
    height: calc(100% - 50px);
    overflow: auto;
    .item {
      margin-bottom: 30px;
      .title {
        // font-size: 145px;
        margin-bottom: 10px;
        font-weight: bold;
      }
    }
  }
  .footer {
    height: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .el-checkbox {
    margin-bottom: 10px;
  }
}
</style>
